import base64
import win32com.client
import os
import sys
import json
import datetime
import time
import jwt

# настройка тестового стенда

'''
CRPT_URL = 'https://markirovka.sandbox.crptech.ru'
CUZ_URL = 'https://suz.sandbox.crptech.ru'
omsConnection='3470da4d-2211-41e2-8e71-9dc561c52bb1'
omsId='956227d3-4fe2-4b9c-ac38-3fd89dbb5313'
'''
# настройка промышленного стенда

CRPT_URL = 'https://markirovka.crpt.ru'
CUZ_URL = 'https://suz.crpt.ru'
omsConnection='9e305a5d-f8c4-40dc-8e0e-273885de03a7'
omsId='f081cfb0-d86b-47a5-9515-84636e4bfd80'


CADES_BES = 1
CADES_DEFAULT = 0
CAPICOM_ENCODE_BASE64 = 0
CAPICOM_CURRENT_USER_STORE = 2
CAPICOM_MY_STORE = 'My'
CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED = 2

ExtensionList=['beer','water','softdrinks']

# Выбираем сертификат 
oStore = win32com.client.Dispatch("CAdESCOM.Store")
oStore.Open(CAPICOM_CURRENT_USER_STORE, CAPICOM_MY_STORE, CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED)

print('Выберите номер сертификата')

for i,val in enumerate(oStore.Certificates):
    print('')
    print(i,val.SubjectName)
    print('')
oCert = oStore.Certificates[int(input())] 
print(oCert.SerialNumber)
print('')


#Создаем объект подписанта
oSigner = win32com.client.Dispatch("CAdESCOM.CPSigner")
oSigner.Certificate = oCert
oSigningTimeAttr = win32com.client.Dispatch("CAdESCOM.CPAttribute")
oSigningTimeAttr.Name = 0
oSigningTimeAttr.Value = datetime.datetime.now()
oSigner.AuthenticatedAttributes2.Add(oSigningTimeAttr)


win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')



# Отправляем запрос на выпуск токена для ЦРПТ , получаем поле data для подписи 
url = CRPT_URL+"/api/v3/true-api/auth/key" 
params = {}
#win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
win_http.Open("GET", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.Send(json.dumps(params))
win_http.WaitForResponse()
items  = json.loads(win_http.ResponseText)
CodeAuth = items['data']

# Формируем прикрепленную подпись для поля data                                   
oSignedData = win32com.client.Dispatch("CAdESCOM.CadesSignedData")
oSignedData.ContentEncoding = 1
message = CodeAuth
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('ascii')
oSignedData.Content = base64_message
sSignedData = oSignedData.SignCades(oSigner, CADES_BES, False, CAPICOM_ENCODE_BASE64)

# Отправляем запрос на получение токена ЦРПТ на основании подписанного поля data
url = CRPT_URL+"/api/v3/true-api/auth/simpleSignIn"
paramskey ={
  'uuid': items['uuid'],
  'data': sSignedData
}
win_http.Open("POST", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.Send(json.dumps(paramskey))
win_http.WaitForResponse()

# получили токен црпт
token_crpt =json.loads(win_http.ResponseText)["token"]
#print(token_crpt)

# Отправляем запрос на выпуск токена для СУЗ , получаем поле data для подписи
url = CRPT_URL+"/api/v3/true-api/auth/key" 
params = {}
win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
win_http.Open("GET", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.Send(json.dumps(params))
win_http.WaitForResponse()
items  = json.loads(win_http.ResponseText)
CodeAuth = items['data']
                                   
# Формируем прикрепленную подпись для поля data
oSignedData = win32com.client.Dispatch("CAdESCOM.CadesSignedData")
oSignedData.ContentEncoding = 1
message = CodeAuth
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('ascii')
oSignedData.Content = base64_message
sSignedData = oSignedData.SignCades(oSigner, CADES_BES, False, CAPICOM_ENCODE_BASE64)

# Отправляем запрос на получение токена СУЗ на основании подписанного поля data
url = CRPT_URL+"/api/v3/true-api/auth/simpleSignIn/"+omsConnection
paramskey ={
  'uuid': items['uuid'],
  'data': sSignedData
}

win_http.Open("POST", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.Send(json.dumps(paramskey))
win_http.WaitForResponse()

# получили токен СУЗ
token_suz =json.loads(win_http.ResponseText)["token"]
#print(token_suz)

print('Выберите товарную группу')
print('-'*30)
print('1 - пиво')
print('2 - вода')
print('3 - безалкоголка')
choice = int(input())-1
extension=ExtensionList[choice]
print('-'*30)
print('Введите Номер документа о нанесении')
resultDocId=input()
print('-'*30)
print('Дата производства в формате год-месяс-день пример 2021-08-07 ')
production_date=input()
print('-'*30)
print('Код ТН ВЭД ЕАС товара')
tnved_code=input()
print('-'*30)
print('Номер документа подтверждающего соответствие')
certificate_number=input()
print('-'*30)
print('Дата документа подтверждающего соответствие год-месяс-день пример 2021-08-07 ')
certificate_date=input()
print('-'*30)
print('Получаем марки из документа Нанесения')

url =CUZ_URL+'/api/v2/'+extension+'/receipts/receipt?resultDocId='+resultDocId+'&omsId='+omsId
params = {}
win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
win_http.Open("GET", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.SetRequestHeader("clientToken",token_suz)
win_http.Send(json.dumps(params))
win_http.WaitForResponse()
docId  = json.loads(win_http.ResponseText)['results'][0]['sourceDocId']

url =CUZ_URL+'/api/v2/'+extension+'/receipts/document?resultDocId='+resultDocId + '&docId='+docId+'&omsId='+omsId
params = {}
win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
win_http.Open("GET", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.SetRequestHeader("clientToken",token_suz)
win_http.Send(json.dumps(params))
win_http.WaitForResponse()
sntins  = json.loads(json.loads(win_http.ResponseText)['content'])['sntins']

print('-'*30)
print('Формируем и отправляем документа о введении в оборот')

csv = '''ИНН участника оборота,ИНН производителя,ИНН собственника,Дата производства,Тип производственного заказа,Версия
4345000224,4345000224,4345000224,'''+production_date+''',Собственное производство,6'''+'''
Параметры товаров
КИ,КИТУ,Дата производства,Код ТН ВЭД ЕАС товара,Вид документа подтверждающего соответствие,Номер документа подтверждающего соответствие,Дата документа подтверждающего соответствие,Номер скважины,Номера лицензий на пользование недрами,Дата выдачи лицензии,Идентификатор ВСД
'''
#ЕАЭС N RU Д-RU.РА04.В.66404/23
#2021-08-07
#2202100000


# Через строковую переменную
#----------------------------------------------------
for i in sntins:
    csv =csv+'"'+i.replace('"','""')+'"'+',,'+production_date+','+tnved_code+',Декларация о соответствии,'+certificate_number+','+certificate_date+',,,,,,\n'
document_base64=base64.b64encode(csv.encode('UTF-8'))
document_base64=document_base64.decode('ascii')
#----------------------------------------------------

'''
# Через файл
#----------------------------------------------------
with open('sntins.csv','w+',-1,'UTF-8') as f:
    f.write(csv)
    for i in sntins:
        f.write('"'+i.replace('"','""')+'"'+',,'+production_date+','+tnved_code+',Декларация о соответствии,'+certificate_number+','+certificate_date+',,,,,,\n')
   
with open('sntins.csv', 'rb') as f:
    document_base64=base64.b64encode(f.read())
    document_base64=document_base64.decode('ascii')
#----------------------------------------------------
'''


#                            
oSignedData = win32com.client.Dispatch("CAdESCOM.CadesSignedData")
oSignedData.ContentEncoding = 1
oSignedData.Content = document_base64
sSignedData = oSignedData.SignCades(oSigner, CADES_BES, True, CAPICOM_ENCODE_BASE64)

#7
url = CRPT_URL+"/api/v3/true-api/lk/documents/create?pg="+extension

paramskey ={
            'type' : 'LP_INTRODUCE_GOODS',
            'document_format' :'CSV',
            'product_document' : document_base64,
            'signature': sSignedData.replace('\r\n','') }
#            'signature': sSignedData.replace('\r\n','') }

win_http.Open("POST", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.SetRequestHeader("Authorization","Bearer "+token_crpt )
win_http.Send(json.dumps(paramskey))
win_http.WaitForResponse()

print('-'*30)
print('Документ отправлен, подучен идентификатор:')
print(uuidDoc := win_http.ResponseText)
print('-'*30)
print('Нажми на любую клавишу для выхода')
exit_code=input()

'''
#time.sleep(1)

url = CRPT_URL+"/api/v4/true-api/doc/list?number="+uuidDoc+"&pg="+extension

params = {}
win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
win_http.Open("GET", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.SetRequestHeader("Authorization",str("Bearer "+token_crpt))
#time.sleep(1)


status = 'IN_PROGRESS'
while status == 'IN_PROGRESS':
    win_http.Send(json.dumps(params))
    win_http.WaitForResponse()
    try:
        status = json.loads(win_http.ResponseText)["results"][0]["status"]
    except:
        status = 'IN_PROGRESS'
    time.sleep(5)
print("    "+status)
#"status":"ACCEPTED"
'''

